import akshare as ak
import pandas as pd
from pyecharts import options as opts
from pyecharts.charts import Kline, Page
from pyecharts.components import Table
from pyecharts.options import ComponentTitleOpts


def get_futures_data(symbol):
    """
    使用 akshare 获取期货日 K 线数据
    :param symbol: 期货品种代码，例如 'SHFE.rb2401'
    :return: 日期列表和 K 线数据列表
    """
    try:
        # 尝试使用 futures_zh_daily_sina 接口
        futures_zh_daily_df = ak.futures_zh_daily_sina(symbol=symbol)
        if futures_zh_daily_df.empty:
            print(f"未能获取到 {symbol} 的数据，可能是期货代码错误或网络问题，请检查。")
            return [], []
        # 转换日期列
        futures_zh_daily_df['date'] = pd.to_datetime(futures_zh_daily_df['date'])
        dates = futures_zh_daily_df['date'].dt.strftime("%Y-%m-%d").tolist()
        kline_data = futures_zh_daily_df[["open", "close", "low", "high"]].values.tolist()
        return dates, kline_data
    except Exception as e:
        print(f"获取 {symbol} 数据时发生错误: {e}")
        return [], []


def create_kline_chart(symbol):
    """
    创建 K 线图
    :param symbol: 期货品种代码
    :return: K 线图对象
    """
    dates, kline_data = get_futures_data(symbol)
    kline = (
        Kline()
        .add_xaxis(dates)
        .add_yaxis(symbol, kline_data)
        .set_global_opts(
            title_opts=opts.TitleOpts(title=f"{symbol} 日 K 线图"),
            xaxis_opts=opts.AxisOpts(is_scale=True),
            yaxis_opts=opts.AxisOpts(
                is_scale=True,
                splitarea_opts=opts.SplitAreaOpts(
                    is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)
                ),
            ),
            datazoom_opts=[opts.DataZoomOpts()],
            toolbox_opts=opts.ToolboxOpts(is_show=True)
        )
    )
    return kline


if __name__ == "__main__":
    # 定义要查询的期货品种列表
    symbols = ["SHFE.rb2510", "DCE.m2509", "CZCE.SR509"]
    page = Page()

    for symbol in symbols:
        chart = create_kline_chart(symbol)
        page.add(chart)

    # 渲染页面
    page.render("futures_kline_charts.html")